<script setup lang="ts">
import { ref, watch, reactive, onBeforeMount, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

import type { FormInstance, FormRules } from 'element-plus'

import { getRoleTableListApi } from '@/api/table/role'
import { getDepartmentTreeListApi } from '@/api/common/department'
import moment from "moment"
import {
  uploadAvatarApi,
  addUserApi,
  editUserApi,
  queryUserRoleApi,
  userDepartListApi
} from '@/api/userManage/index'
import type { UploadProps } from 'element-plus'
// 定义props接口
interface iProps {
  drawer: boolean
  title?: string
  ruleFormProps?: any
  drawerType: number //新增1，编辑2，详情3
}
// 定义emit接口
interface iEmits {
  (e: 'updateDrawer', params: boolean): void
  (e: 'updateUserList'): void
}
// props初始化
let props = withDefaults(defineProps<iProps>(), {
  drawer: false,
  title: '新增',
  ruleFormProps: null,
  drawerType: 1
})
// emit初始化
let emits = defineEmits<iEmits>()

// 定义双向绑定的drawer状态
let drawerStatus = ref(props.drawer)

// 监听 drawer 的变化
watch(
  () => props.drawer,
  (newVal) => {
    drawerStatus.value = newVal
  }
)
//
const handleClose = (done: () => void) => {
  drawerStatus.value = false
  emits('updateDrawer', false)
  done()

  if (!ruleFormRef.value) return
  ruleFormRef.value.resetFields()
}
// 取消、关闭
const cancelClick = (formEl: FormInstance | undefined) => {
  emits('updateDrawer', false)
  if (!formEl) return
  formEl.resetFields()
  // 发射事件关闭抽屉
}
// 表单提交事件
const confirmClick = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 新增
      if (props.drawerType == 1) {
        postAddUserApi()
      }
      // 编辑
      else if (props.drawerType == 2) {
        postEditUserApi()
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
const postEditUserApi = async () => {
  let params: any = JSON.parse(JSON.stringify(ruleForm))
  if(ruleForm.birthday){
    params.birthday = moment(ruleForm.birthday).format('YYYY-MM-DD')
  }
  params.departIds = params.departIds.join(',')
  params.roleIds = params.roleIds.join(',')
  params.id = props.ruleFormProps.id
  let rst = await editUserApi(params)
  let { code, success } = rst || {}
  if (code == 200 && success) {
    ElMessage.success('编辑添加成功')
    emits('updateDrawer', false)
    emits('updateUserList')
    if (!ruleFormRef.value) return
    ruleFormRef.value.resetFields()
  } else {
    ElMessage.error('编辑添加失败')
  }
}
const postAddUserApi = async () => {
  let params: any = JSON.parse(JSON.stringify(ruleForm))
  params.departIds = params.departIds.join(',')
  params.roleIds = params.roleIds.join(',')
  let rst = await addUserApi(params)
  let { code, success } = rst || {}
  if (code == 200 && success) {
    ElMessage.success('用户添加成功')
    emits('updateDrawer', false)
    emits('updateUserList')
    if (!ruleFormRef.value) return
    ruleFormRef.value.resetFields()
  } else {
    ElMessage.error('用户添加失败')
  }
}
/***************************表单处理*************************** */
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  username: '', //账号
  password: '', //密码
  repassword: '', //确认密码
  workNo:'',//工号
  realname: '', //姓名
  phone: '', //手机
  roleIds: [], //角色 多选
  departIds: [], //部门 多选
  avatar: '', //头像
  birthday: '', //生日
  sex: '', //性别
  email: '', //邮箱
  telephone: '' //座机
})
/* 验证手机号 */
const isMobileNumber = (rule, value, callback) => {
  if (!value) {
    return new Error('请输入电话号码')
  } else {
    const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
    const isPhone = reg.test(value)
    value = Number(value) //转换为数字
    if (typeof value === 'number' && !isNaN(value)) {
      //判断是否为数字
      value = value.toString() //转换成字符串
      if (value.length < 0 || value.length > 12 || !isPhone) {
        //判断是否为11位手机号
        callback(new Error('手机号码格式如:138xxxx8754'))
      } else {
        callback()
      }
    } else {
      callback(new Error('请输入电话号码'))
    }
  }
}
/* 验证邮箱 */
const isEmail = (rule, value, callback) => {
  if (!value) {
    callback()
  } else {
    const reg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/
    const email = reg.test(value)
    if (!email) {
      callback(new Error('邮箱格式如:admin@163.com'))
    } else {
      callback()
    }
  }
}
/* 验证确认密码 */
const equalToPassword = (rule, value, callback) => {
  if (ruleForm.password !== value) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户账号', trigger: 'blur' },
    { min: 3, max: 30, message: '长度限制在3到30', trigger: 'blur' }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    },
    { min: 6, max: 20, message: '密码长度最小6位，最大20位', trigger: 'blur' },
    {
      trigger: 'blur',
      validator: (rule, value, callback) => {
        var passwordreg = /(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\W])/
        if (!passwordreg.test(value)) {
          callback(new Error('密码必须含数字、字母和特殊符号，最小6位，最大20位'))
        }else{
          callback()
        }
      } 
    }
  ],
  repassword: [
    { required: true, message: '确认密码不能为空', trigger: 'blur' },
    { required: true, validator: equalToPassword, trigger: 'blur' }
  ],
  realname: [
    { required: true, message: '请输入用户姓名', trigger: 'blur' },
    { min: 1, max: 30, message: '长度限制在1到30', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { validator: isMobileNumber, trigger: 'blur' }
  ],
  email: [{ validator: isEmail, trigger: 'blur' }]
})

/******************************头像处理************************************** */
const handleFileUpload = async ({ file }) => {
  let rst = await uploadAvatarApi(file)
  let { data } = rst
  if (data.code == 200 && data.success) {
    ruleForm.avatar = data.result
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(`文件上传失败，${data.message}`)
  }
}
// const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
//   ruleForm.avatar = URL.createObjectURL(uploadFile.raw!)
// }

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log('---rawFile.type--------', rawFile.type)
  if (rawFile.type != 'image/jpeg' && rawFile.type != 'image/png') {
    ElMessage.error('图片格式限定为jpeg或png')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('头像图片最大不超过5M')
    return false
  }
  return true
}
/*******************************菜单处理*************************************** */
const departOptions = ref([]) //部门树
const defaultCheckedKeys = ref<Array<string>>([]) //默认勾选的部门数组

const roleOptions = ref<
  Array<{
    id: string
    roleName: string
  }>
>([])

/**************************生命周期***************************** */
const getRoleList = async () => {
  let rst = await getRoleTableListApi({
    pageNo: 1,
    pageSize: 1000
  })
  let { code, result } = rst
  if (Number(code) == 200) {
    roleOptions.value = result.records
  }
}
const getDepartmentTreeList = async () => {
  let rst = await getDepartmentTreeListApi()
  let { code, result, success } = rst
  if (Number(code) == 0 && success) {
    departOptions.value = result
  }
}
const getUserRoles = async (userid: string) => {
  let rst = await queryUserRoleApi({ userid })
  let { code, result, success } = rst
  if (code == 0 && success) return result
  return []
}
const getUserDepars = async (userId: string) => {
  let rst = await userDepartListApi({ userId })
  let { code, result, success } = rst
  if (code == 0 && success) {
    let keys: Array<string> = []
    for (let item of result) {
      keys.push(item.key)
    }
    return keys
  }
  return []
}
// 表单回显
const echoRuleForm = async () => {
  let id = props.ruleFormProps.id
  let roles = await getUserRoles(id)
  let depars: Array<string> = await getUserDepars(id)
  defaultCheckedKeys.value = depars

  ruleForm.username = props.ruleFormProps.username //账号
  ruleForm.workNo = props.ruleFormProps.workNo //工号
  ruleForm.realname = props.ruleFormProps.realname //姓名
  ruleForm.phone = props.ruleFormProps.phone //手机
  ruleForm.roleIds = roles //角色 多选
  ruleForm.departIds = depars //部门 多选
  ruleForm.avatar = props.ruleFormProps.avatar //头像
  ruleForm.birthday = props.ruleFormProps.birthday //生日
  if (props.ruleFormProps.sex)
    ruleForm.sex = props.ruleFormProps.sex == 0 ? '' : props.ruleFormProps.sex.toString() //性别
  ruleForm.email = props.ruleFormProps.email //邮箱
  ruleForm.telephone = props.ruleFormProps.telephone //座机
}

onBeforeMount(() => {
  getRoleList()
  getDepartmentTreeList()
})
onMounted(() => {
  // 编辑或详情的回显
  if (props.ruleFormProps) {
    echoRuleForm()
  }
})
</script>
<template>
  <el-drawer
    v-model="drawerStatus"
    direction="rtl"
    :before-close="handleClose"
    :destroy-on-close="true"
  >
    <template #header>
      <h4>{{ props.title }}</h4>
    </template>
    <template #default>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="用户账号" prop="username">
          <el-input v-model.trim="ruleForm.username" :disabled="props.drawerType == 2" />
        </el-form-item>
        <el-form-item label="登录密码" prop="password" v-if="props.drawerType == 1">
          <el-input type="password" show-password v-model.trim="ruleForm.password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="repassword" v-if="props.drawerType == 1">
          <el-input type="password" show-password v-model.trim="ruleForm.repassword" />
        </el-form-item>
        <el-form-item label="工号" prop="workNo">
          <el-input v-model.trim="ruleForm.workNo" />
        </el-form-item>
        <el-form-item label="用户姓名" prop="realname">
          <el-input v-model.trim="ruleForm.realname" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model.trim="ruleForm.phone" />
        </el-form-item>
        <el-form-item label="角色分配" prop="roleIds">
          <el-select
            v-model="ruleForm.roleIds"
            multiple
            collapse-tags
            placeholder="请选择角色"
            style="width: 240px"
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门分配" prop="departIds">
          <el-tree-select
            v-model="ruleForm.departIds"
            :data="departOptions"
            :default-expand-all="drawerType == 2 || drawerType == 3"
            node-key="id"
            :default-checked-keys="defaultCheckedKeys"
            :props="{ label: 'departName' }"
            :check-strictly="true"
            multiple
            :render-after-expand="false"
            show-checkbox
          />
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :http-request="handleFileUpload"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="ruleForm.avatar" :src="ruleForm.avatar" style="width: 80px; height: 80px" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker v-model="ruleForm.birthday" type="date" placeholder="请选择生日" />
        </el-form-item>

        <el-form-item label="性别">
          <el-select v-model="ruleForm.sex" placeholder="请选择性别">
            <el-option label="男" value="1" />
            <el-option label="女" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email" />
        </el-form-item>
        <el-form-item label="座机">
          <el-input v-model="ruleForm.telephone" />
        </el-form-item>
      </el-form>
    </template>
    <template #footer v-if="props.drawerType != 3">
      <div style="flex: auto">
        <el-button @click="cancelClick(ruleFormRef)">关闭</el-button>
        <el-button type="primary" @click="confirmClick(ruleFormRef)">提交</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<style lang="less" scoped>
:deep(.avatar-uploader .el-upload) {
  border: 1px dashed #ccc;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
}
</style>
